from dataclasses import dataclass
from typing import TypeVar, Generic, List

from pydantic import Field

from core.utils.pydantic_model import GlobalBaseModel

# 定义泛型类型
T = TypeVar('T')


@dataclass
class Order(object):
    field: str

    desc: bool


class QueryModel(GlobalBaseModel, Generic[T], object):
    pageIndex: int = Field(default=0)

    pageSize: int = Field(default=10)

    param: T = Field(default=None)

    orders: List[Order] = Field(default_factory=list)

    def get_start_row_index(self) -> int:
        return 0 if self.pageIndex <= 0 else self.pageSize - 1

    # def model_dump(self, **kwargs) -> dict:
    #     """
    #     对象转换成 dict
    #     :param kwargs:
    #     :return:
    #     """
    #     data = super().model_dump(**kwargs)
    #     # 在这里对这个dict添加属性
    #     data.update({'startRow': self.get_start_row_index()})
    #     return data

# if __name__ == '__main__':
# 创建对象，QueryModel接受一个泛型类型，用[] 表示
# query = QueryModel[Order](pageIndex=1, pageSize=10, param=Order(field='name', desc=True), orders=[])
# val = query.model_dump(by_alias=True)
# # indent: 缩进，默认为一行输出
# # include:  一个set类型，包含哪些字段
# # exclude:  一个set类型，排除哪些字段
# # print("转换为json str : \n%s" % (
# #     query.model_dump_json(indent=4, by_alias=True, include={"page_index", "param", "orders"}, exclude={"a"})))
# print("转换为json str : \n%s" % (
#     query.model_dump_json(by_alias=True)))
# obj = QueryModel[Order].parse_raw(query.model_dump_json(by_alias=True))  # json str转换成对象
#
# print(isinstance(obj.param, Order))  # 反序列后，类型是否为Order类型
